package com.xiangwei.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;



import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;










import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xiangwei.service.IAdminService;
import com.xiangwei.service.IQrcodeService;
import com.xiangwei.service.ISummaryService;
import com.xiangwei.util.Common;
import com.xiangwei.util.ReadPropertiesUtil;
import com.xiangwei.view.EchartsView;
import com.xiangwei.entity.Admin;
import com.xiangwei.entity.Summary;
@Controller
@RequestMapping(value = "admin")
public class AdminController extends BaseController{
    private static final Logger logger = LoggerFactory.getLogger(AdminController.class);

	@Autowired
    private IAdminService adminService;
	@Autowired
    private IQrcodeService qrcodeService;
	@Autowired
    private ISummaryService summaryService;

    /**
     * 进入登录页面
     * @return
     */
    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String login() {
        return "admin/login";
    }
    
    /**
     * 登录
     * @param admin
     * @param model
     * @return
     * @throws Exception 
     */
    @RequestMapping(value = "logining", method = RequestMethod.POST)
    public String logining(Admin admin, Model model,HttpSession session) throws Exception {
 
    	Admin ad = adminService.getAdmin(admin);
            if (ad != null) {
            		session.removeAttribute("admin");
    				session.setAttribute("admin", ad);
    		}else{
    			String message = URLEncoder.encode("用户名或密码错误", "utf-8");
    			logger.error("用户名或密码错误");
    			return "redirect:login?message=" + message;
    		}
            logger.info("登录成功");
        return "redirect:index";
    }
    
    /**
     * 首页
     * @return
     */
    @RequestMapping(value = "index", method = RequestMethod.GET)
    public String index(Model model) {

    	Summary summary = summaryService.selectSummary();
    	model.addAttribute("summary", summary);
        return "admin/index";
    }
    
    /**
	 * 刷新首页的数据
	 * @param session
	 * @param response
	 * @param days
	 */
	@RequestMapping(value = "reloadechart", method = RequestMethod.POST)
	public void reloadEchart(HttpServletResponse response, String days) {
		Map<String, Object> paraMap = new HashMap<String, Object>();
		paraMap.put("days", Integer.parseInt(days));
		//统计图数据取得
		EchartsView ehv = summaryService.selectECharts(paraMap);
		// 数据返回至页面
		try {
			response.getWriter().write(JSON.toJSON(ehv).toString());
		} catch (IOException e) {
			logger.error(e.getMessage());
		}
	}
    
	/**
	 * 注销登陆
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "logout", method = RequestMethod.GET)
	public String logOut(HttpSession session) {
		session.removeAttribute("admin");
		return "redirect:login";
	}
	
	@RequestMapping(value = "adminList", method = RequestMethod.GET)
	public String adminList(HttpSession session,Model model) {
		Admin admin = (Admin) session.getAttribute("admin");
		List<Admin> list = adminService.findAdminList(admin);
		model.addAttribute("adminList", list);
		return "admin/adminList";
	}
	
	/**
	 * 用户列表
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "findAdminList", method = RequestMethod.GET)
	public void adminList(HttpSession session,HttpServletResponse response) {
		Admin admin = (Admin) session.getAttribute("admin");
		List<Admin> adminList = adminService.findAdminList(admin);
		try {
			PrintWriter out = response.getWriter();
			JSONObject data = new JSONObject();
			data.put("adminList", adminList);
			out.print(data);
		} catch (IOException e) {
			logger.error(e.getMessage());
		}
	}
    
	/**
	 *编辑用户初始化
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "updateInit", method = RequestMethod.POST)
	public void updateInit(String id, HttpServletResponse response) {

		Admin admin = new Admin();
		admin = adminService.selectByPrimaryKey(id);
		String json = JSONObject.toJSONString(admin);
		try {
			response.getWriter().write(json);
		} catch (IOException e) {
			logger.error(e.getMessage(),e);
			e.printStackTrace();
		}
	}
    
	/**
	 *删除操作
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "deleteUser", method = RequestMethod.POST)
	public void deleteUser(String id, HttpServletResponse response,HttpSession session) {
		Admin ad = (Admin) session.getAttribute("admin");
//		Admin admin = adminService.selectByPrimaryKey(id);
		String msg = "fail";
		if(ad.getRole() != 2){
			logger.error("权限不足");	

		}else{
			int count = adminService.deleteByPrimaryKey(id);
			if(count > 0){
				msg = "success";
				try {
					response.getWriter().write(msg);
				} catch (IOException e) {
					logger.error(e.getMessage());
				}
			}else{
				logger.error("删除失败");
			}			
		}
		
	}
	
	/**
     * 保存修改密码
     * @param vendorId
     * @param response
     */
    @RequestMapping(value = "savePwd", method = RequestMethod.POST)
    public void savePwd(Admin admin,HttpServletResponse response){
    	int count = adminService.savePwd(admin);
    	if(count > 0){
    		try {
    			response.getWriter().print("success");
    		} catch (IOException e) {
    			logger.error(e.getMessage(), e);
    			e.printStackTrace();
    		}
    	}
    }
    
    /**
	 *用户保存
	 * @param admin
	 * @return
	 */
	@RequestMapping(value = "saveAdmin", method = RequestMethod.POST)
	public String saveAdmin(Admin admin, Model model) {
		int count = adminService.saveAdmin(admin);
		if(count >0){
			logger.info("保存成功");
		}else{
			logger.info("保存失败");
		}
		return "redirect:adminList";
	}
	
	/**
	 *禁用/启用操作
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "fobidUser", method = RequestMethod.POST)
	public void fobidUser(String id, String status, HttpServletResponse response) {
		Admin admin = new Admin();
		if(!Common.isEmptyString(id) && !Common.isEmptyString(status)){
			logger.error("传入参数为空");
			return;
		}
		admin.setId(Short.parseShort(id));
		admin.setStatus(Integer.parseInt(status));
		int count = adminService.updateByPrimaryKeySelective(admin);
		
		
		if(count > 0){
			try {
				response.getWriter().write("success");
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
				e.printStackTrace();
			}
		}else{
			logger.error("修改失败");
		}
	}
	
	 /**
     * 判断原密码输入是否正确
     * @param vendorId
     * @param response
     * @throws IOException 
     */
    @RequestMapping(value = "checkPwd", method = RequestMethod.POST)
    public void checkPwd(String oldPassword,HttpServletResponse response,HttpSession session) throws IOException{
    	Admin admin = (Admin) session.getAttribute("admin");
    	int count = adminService.checkPwd(admin,oldPassword);
    	if(count == 1){
    		try {
    			response.getWriter().print("success");
    		} catch (IOException e) {
    			logger.error(e.getMessage(), e);
    			e.printStackTrace();
    		}
    	}else{
    		response.getWriter().print("faild");
    		logger.error("原密码输入错误");
    	}
    }
    
    /**
     * 判断是否是重复的用户名称
     * @param vendorId
     * @param response
     */
    @RequestMapping(value = "checkUserName", method = RequestMethod.POST)
    public void findUserNameCount(String username,String id,HttpServletResponse response){  
    	logger.info(username);
    	String msg = "fail";
    	int count = adminService.findUserNameCount(username,id);
    	if(count == 0){
    		 msg = "success";   				
    	}
    	try {
    		response.getWriter().print(msg);
    	} catch (IOException e) {
    		logger.error(e.getMessage(), e);
    		e.printStackTrace();
    	}
    }
    
    /**
     * 判断是否是重复的用户名称
     * @param vendorId
     * @param response
     */
    @RequestMapping(value = "updateUrl", method = RequestMethod.POST)
    public void updateUrl(String url,HttpServletResponse response){  
    	logger.info(url);
    	if(!Common.isEmptyString(url)){
    		return;
    	}
    	ReadPropertiesUtil.writeData("config.properties", "url", url);
    	try {
			response.getWriter().print("success");
		} catch (IOException e) {
			logger.error(e.getMessage());
		}
    }
    
}